import React, {Component} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ActivityIndicator,
    DeviceEventEmitter, ScrollView,
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Constant from '../../utils/Constant'; //全局变量
import Header from '../../components/header';
import Loading from '../../utils/Loading';
import NoData from '../../utils/NoData';
import {getImgUrl} from '../../utils/ComFunction';
import moment from 'moment';
import RegionPickerView from "../../components/Tool/RegionAllPickerView";
import AndroidModule from "../../utils/AndroidConnent";
import SeekItemView from "./seekComponents/SeekItemView";
import AlertCommonView from "../../components/Tool/AlertCommonView";
import {ToastToUser} from "../../utils/CustomToast";
import LinearGradient from 'react-native-linear-gradient';
import StatusBarSelf from "../../components/StatusBarSelf";
import ZhuanYinItemView from "./seekComponents/ZhuanYinItemView";
import SinglePicker from "../../components/Tool/SinglePicker";

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class SeekingListPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedTab: 1,

            buyerLists: [],
            myFollowBuyerList: [],

            showCityPicker: false, // 城市弹出

            showReadMore: false,

            seekingList: [],
            zhuanYinList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            pageSize: 20,

            // 搜索条件
            areaId: null,
            brandId: null,
            mileageMin: null,
            mileageMax: null,
            registerDateBegin: null,
            registerDateEnd: null,
            carPriceMin: null,
            carPriceMax: null,
            carOutColor: [],
            carOutColorPr: [],
            carInColor: [],
            carInColorPr: [],
            title: null,


            filterShowList: [], // 条件列表

            // 弹窗
            showAlertCommonView: false,
            showAlertData: {},
            deleteId: null,
            upCarPurchaseId: null, // 当前上下架id

            // 专营类型
            zhuanYinType: [],
            merchantTypeShow: false,
            zyCity: '',
            zyType: '',
            zhuanYinCity: [],
            merchantCityShow: false,

        };
    }

    componentDidMount() {
        // 搜索监听
        this.serchingPage = DeviceEventEmitter.addListener('commonEvent', (data) => {
            if(data.type === 'search' && data.fromPage === 'SeekingListPage'){
                let keywordObj = {
                    title: data.keyword,
                    key: 'title',
                    value: data.keyword
                }
                this.addRenderFilter(keywordObj)
                this.setState({
                    title: data.keyword ? data.keyword : null,
                },() => {
                    this.refreshData();
                })
            }
            // 刷新关注数据
            if(data.type === 'follow' && data.fromPage === 'BuyerInfoPage'){
                console.log('刷新关注数据')
                this.getMyFollowBuyerList()
            }
        })

        // 添加求购监听
        this.ApplyCarFormPage = DeviceEventEmitter.addListener('ApplyCarFormPageSave', (data) => {
            if(data.fromPage === 'SeekingListPage'){
                this.refreshData()
            }
        })

        // 筛选条件监听
        this.SeekMoreFilterPage = DeviceEventEmitter.addListener('SeekMoreFilterPage', (data) => {
            if(data.type === 'seekMoreFilter'){
                this.addAllFilterShow(data)
            }
        })

        // 品牌事件监听
        this.selectBrandResult = DeviceEventEmitter.addListener('selectBrandResult', (result) => {
            if (result && result.from === 'SeekingListPage') {
                this.formatBrand(result)
            }
        })

        // 添加页面焦点监听，确保每次进入页面都刷新数据
        this.focusListener = this.props.navigation.addListener('focus', () => {
            // 更新咨询人数
            if(Constant.userInfo.buyerId > 0 && this.state.seekingList.length > 0){
                const updateIds = [];
                this.state.seekingList.map(item => {
                    if(item.buyerId === Constant.userInfo.buyerId){
                        updateIds.push(item.id)
                    }
                })
                if(updateIds.length > 0){
                    this.updateSeekingList(updateIds)
                }
            }
            // 更新底部的未读消息数量
            setTimeout(() => {
                DeviceEventEmitter.emit('updateViewCarCount');
            }, 2000)
        });

        this.checkUserIsBuyer()
        this.getZhuanYinType()
        this.getZhuanYinCity()
    }

    componentWillUnmount() {
        if (this.SeekMoreFilterPage) { // 移除筛选条件监听
            this.SeekMoreFilterPage.remove();
        }
        if (this.selectBrandResult) {
            this.selectBrandResult.remove();
        }
        if (this.serchingPage) {
            this.serchingPage.remove();
        }
        if (this.focusListener) {
            this.focusListener();
        }
    }

    render() {
        navigation = this.props.navigation;
        let height = isIos ? 44:49;
        return (
            <View style={styles.container}>
                {/*<StatusBarSelf color={'#fff'}/>*/}
                <Header navigation={navigation} Title={()=> this.renderTitle()} RightButton={() => this.renderRightButton()} />

                {/*<View style={{width: '100%', flexDirection: 'row',*/}
                {/*    backgroundColor: '#fff', paddingHorizontal: 10,*/}
                {/*    paddingVertical: 10, height: height,*/}
                {/*    borderBottomWidth: 0.5, borderColor: '#E5E5E5'}}>*/}
                {/*    <View style={{width: '50%'}}>*/}
                {/*        {this.renderTitle()}*/}
                {/*    </View>*/}
                {/*    <View style={{width: '50%'}}>*/}
                {/*        {this.renderRightButton()}*/}
                {/*    </View>*/}
                {/*</View>*/}

                {/* 找买手 or 已经关注的买手 */}
                {this.state.selectedTab < 3 ? this.buyerList() : null}

                {/* 搜索 */}
                {this.state.selectedTab < 3 ? this.renderFilter() : this.renderFilterZY()}

                {/* 未读的求购信息数量 */}
                {this.renderNoViewSeeking()}

                {/* 条件清除 */}
                {this.renderFilterShow()}

                {/* 列表数据 */}
                {this.state.selectedTab < 3 ? this.renderList() : this.renderListZY()}

                {/* 添加求购 */}
                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        console.log(item);
                        let address = item.provinceName + item.cityName
                        let areaId = item.cityId
                        if(item.cityId === 0){ // 不限
                            areaId = item.provinceId
                        }
                        let addressObj = {
                            title: address,
                            key: 'address',
                            value: areaId
                        }
                        this.addRenderFilter(addressObj)
                        this.setState({
                            showCityPicker: false,
                            areaId: areaId,
                        }, function () {
                            this.refreshData()
                        })
                    }}
                />

                {/* 弹窗提示 */}
                {
                    this.state.showAlertCommonView ?
                        <AlertCommonView
                            title={this.state.showAlertData.title}
                            content={this.state.showAlertData.content}
                            cancelBtnText={this.state.showAlertData.cancelBtnText}
                            sureBtnText={this.state.showAlertData.sureBtnText}
                            cancelHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                            }}
                            sureHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                                if (this.state.showAlertData.type === 'delete') {
                                    this.deleteCarPurchase()
                                }else if (this.state.showAlertData.type === 'up') { // 上架求购信息
                                    this.upCarPurchase()
                                }else if (this.state.showAlertData.type === 'down') { // 下架求购信息
                                    this.downCarPurchase()
                                }
                            }}
                        />
                        :
                        null
                }

                {this.state.merchantTypeShow && (
                    <SinglePicker
                        pickerData={this.state.zhuanYinType}
                        onPickerCancel={() => {
                            this.setState({
                                merchantTypeShow: false
                            })
                        }}
                        onPickerConfirm={(name) => {
                            this.setState({
                                zyType: name[0],
                                merchantTypeShow: false
                            }, ()=>{
                                let brandObj = {
                                    title: name[0],
                                    key: 'zyType',
                                    value: name[0]
                                }
                                this.addRenderFilter(brandObj)
                                this.refreshData()
                            })
                        }}
                    ></SinglePicker>
                )}

                {this.state.merchantCityShow && (
                    <SinglePicker
                        pickerData={this.state.zhuanYinCity}
                        onPickerCancel={() => {
                            this.setState({
                                merchantCityShow: false
                            })
                        }}
                        onPickerConfirm={(name) => {
                            this.setState({
                                zyCity: name[0],
                                merchantCityShow: false
                            },()=> {
                                let brandObj = {
                                    title: name[0],
                                    key: 'zyCity',
                                    value: name[0]
                                }
                                this.addRenderFilter(brandObj)
                                this.refreshData()
                            })
                        }}
                    ></SinglePicker>
                )}

                <Loading onRef={ref => (this.Loading = ref)} />
            </View>
        );
    }

    // 未读求购数量
    renderNoViewSeeking() {
        return (
            <View>
                {Constant.noViewSeekingCount > 0 ?
                    <View style={{backgroundColor: '#FFFBE8'}}>
                        <Text style={{height: 30, lineHeight: 30, color: '#ED6A0C', paddingHorizontal: 15, textAlign: 'center'}}>{Constant.noViewSeekingCount} 条新信息</Text>
                    </View>
                    : null}
            </View>
        );
    }

    // 删除求购
    deleteCarPurchase(){
        HttpUtils.postRequest(HttpUrls.deleteCarPurchase, {
            id: this.state.deleteId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("删除成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    upCarPurchase(){
        console.log('upCarPurchase', '上架')
        HttpUtils.postRequest(HttpUrls.upCarPurchase, {
            id: this.state.upCarPurchaseId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("上架成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    downCarPurchase(){
        console.log('upCarPurchase', '下架')
        HttpUtils.postRequest(HttpUrls.downCarPurchase, {
            id: this.state.upCarPurchaseId
        }).then(result => {
            console.log(result)
            if(result.code === 0){
                ToastToUser("下架成功")
                this.refreshData()
            }else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
    }

    // 顶部tab切换
    renderTitle(){
        const { selectedTab } = this.state;

        return (
            <View style={styles.tabContainer}>

                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => this.switchTab(3)}
                    style={styles.tabItem}
                >
                    <Text style={[
                        styles.tabText,
                    ]}>专营</Text>
                    <View style={[
                        styles.underline,
                        selectedTab === 3 && styles.tabActiveBackground
                    ]} />
                </TouchableOpacity>

                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => this.switchTab(1)}
                    style={[styles.tabItem, { marginLeft: 30 }]}
                >
                    <Text style={[
                        styles.tabText,
                    ]}>推荐</Text>
                    <View style={[
                        styles.underline,
                        selectedTab === 1 && styles.tabActiveBackground
                    ]} />
                </TouchableOpacity>

                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => this.switchTab(2)}
                    style={[styles.tabItem, { marginLeft: 30 }]}
                >
                    <Text style={[
                        styles.tabText,
                    ]}>关注</Text>
                    <View style={[
                        styles.underline,
                        selectedTab === 2 && styles.tabActiveBackground
                    ]} />
                </TouchableOpacity>
            </View>
        );
    }

    switchTab(tabIndex){
        console.log('切换tab', tabIndex);
        if (this.state.selectedTab === tabIndex) return; // 如果已经是当前 tab，则不处理

        this.setState({
            selectedTab: tabIndex
        }, function () {
            this.refreshData()
        })
    }

    // 右侧搜索图标
    renderRightButton(){
        return (
            <View style={styles.topRightContain}>
                <TouchableOpacity
                    style={{ marginRight: 8}}
                    onPress={() => {
                        navigation.navigate('SearchPage', { fromPage: 'SeekingListPage', placeholder: '请输入求购内容' })
                    }}>
                    <Image style={styles.iconImgUser} source={require('source/image/seekCenter/search_icon.png')}></Image>
                </TouchableOpacity>

                {Constant.userInfo.buyerId > 0 && (
                    <TouchableOpacity
                        style={{ marginRight: 8}}
                        onPress={() => {
                            navigation.navigate('BuyerDetailPage', {
                                buyerId: Constant.userInfo.buyerId,
                            });
                        }}>
                        <Image style={styles.iconImgUser} source={require('source/image/seekCenter/user_center_icon.png')}></Image>
                    </TouchableOpacity>
                )}

                {Constant.userInfo.buyerId > 0 && (
                    <TouchableOpacity
                        style={{ marginRight: 8}}
                        onPress={() => {
                            navigation.navigate('ApplyCarFormPage', {
                                fromPage: 'SeekingListPage',
                            });
                        }}>
                        <Image style={styles.iconImgUser23} source={require('source/image/seekCenter/seek_add_icon.png')}></Image>
                    </TouchableOpacity>
                )}

            </View>
        );
    };

    renderFilterZY() {
        return (
            <View style={styles.filterContain}>
                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        this.setState({
                            merchantCityShow: true
                        })
                    }}>
                    <Text style={styles.filterText}>城市</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>

                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        this.setState({
                            merchantTypeShow: true
                        })
                    }}>
                    <Text style={styles.filterText}>专营类型</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
            </View>
        )
    }

    // 搜索过滤
    renderFilter() {
        return (
            <View style={styles.filterContain}>
                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        this.setState({
                            showCityPicker: true
                        })
                    }}>
                    <Text style={styles.filterText}>城市</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>

                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        let params = { from: 'SeekingListPage',  selectLevel: 2 }
                        AndroidModule.selectBrand(params, (error, result) => {
                            this.formatBrand(result)
                        })
                    }}>

                    <Text style={styles.filterText}>品牌</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>

                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        navigation.navigate('SeekMoreFilterPage', {
                            fromPage: 'SeekingListPage',

                            mileageMin: this.state.mileageMin,
                            mileageMax: this.state.mileageMax,
                            registerDateBegin: this.state.registerDateBegin,
                            registerDateEnd: this.state.registerDateEnd,
                            carPriceMin: this.state.carPriceMin,
                            carPriceMax: this.state.carPriceMax,
                            carOutColor: this.state.carOutColor,
                            carInColor: this.state.carInColor,
                        })
                    }}>
                    <Text style={styles.filterText}>更多</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
            </View>
        )
    }

    formatBrand(result) {

        console.log('formatBrand result = ', result)
        let brandId = result.seriesId
        let brandName = result.seriesName
        if(result.brandId === 0){
            return
        }
        if(!result.seriesId || result.seriesId === 0){
            brandId = result.brandId
            brandName = result.brandName
        }
        let brandObj = {
            title: brandName,
            key: 'brand',
            value: brandId
        }
        this.addRenderFilter(brandObj)

        this.setState({
            brandId: brandId,
        }, function () {
            this.refreshData()
        })

    }

    addAllFilterShow(data) {
        let tempList = []
        let resultList = []

        console.log("addAllFilterShow ====",  data)

        let mileShowText = data.mileShowText
        let mileageMin = data.mileageMin
        let mileageMax = data.mileageMax

        if (mileShowText === '不限') {
            mileageMin = null
            mileageMax = null
        } else {
            tempList.push({
                title: mileShowText,
                key: 'mileage',
                value: 0
            })
        }

        let ageShowText = data.ageShowText
        let registerDateBegin = data.registerDateBegin
        let registerDateEnd = data.registerDateEnd

        if (ageShowText === '不限') {
            registerDateBegin = null
            registerDateEnd = null
        } else {
            tempList.push({
                title: ageShowText,
                key: 'carAge',
                value: 0
            })
        }

        // 价格
        let priceShowText = data.priceText
        let carPriceMin = data.carPriceMin
        let carPriceMax = data.carPriceMax
        if(priceShowText === '不限'){
            carPriceMin = null
            carPriceMax = null
        }else {
            tempList.push({
                title: priceShowText,
                key: 'price',
                value: 0
            })
        }

        // 颜色
        if(data.carOutColor && data.carOutColor.length > 0){
            data.carOutColor.map((item, index) => {
                let tempListItem = {
                    title: item,
                    key: 'carOutColor',
                    value: item
                }
                tempList.push(tempListItem)
            })
        }

        // 颜色
        if(data.carInColor && data.carInColor.length > 0){
            data.carInColor.map((item, index) => {
                let tempListItem = {
                    title: item,
                    key: 'carInColor',
                    value: item
                }
                tempList.push(tempListItem)
            })
        }

        let filterShowList = this.state.filterShowList
        if (filterShowList.length === 0) {
            resultList = tempList
        } else {
            let temp = [];
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key === 'keyword' || filterShowList[i].key === 'brand') {
                    temp.push(filterShowList[i])

                }
            }
            resultList = temp.concat(tempList)

        }

        resultList.push({ key: 'clear' })

        this.setState({
            filterShowList: resultList,
            // 公里数
            mileageMin: mileageMin,
            mileageMax: mileageMax,

            // 车龄
            registerDateBegin: registerDateBegin,
            registerDateEnd: registerDateEnd,

            carPriceMin: carPriceMin,
            carPriceMax: carPriceMax,

            carOutColor: data.carOutColor,
            carOutColorPr: data.carOutColorPr,

            carInColor: data.carInColor,
            carInColorPr: data.carInColorPr,

        })

        this.refreshData();
    }

    // 条件清除
    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()
                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)
                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    addRenderFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)
        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }
            if (!isExist) {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
            }
        }

        this.setState({
            filterShowList: filterShowList
        })
    }

    // 条件清除
    clearFilterShow() {
        this.setState({
            filterShowList: [],
            areaId: null,
            brandId: null,
            mileageMin: null,
            mileageMax: null,
            registerDateBegin: null,
            registerDateEnd: null,
            carPriceMin: null,
            carPriceMax: null,
            carOutColor: [],
            carInColor: [],
            title: null,
            zyCity: null,
            zyType: null
        }, function () {
            this.refreshData()
        })
    }

    // 删除条件
    removeFilterShow(item, index) {
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i !== index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key === 'address') {
            this.setState({
                areaId: null
            })
        }
        if (item.key === 'brand') {
            this.setState({
                brandId: null
            })
        }
        if(item.key === 'mileage'){
            this.setState({
                mileageMin: null,
                mileageMax: null
            })
        }
        if(item.key === 'carAge'){
            this.setState({
                registerDateBegin: null,
                registerDateEnd: null
            })
        }
        if(item.key === 'price'){
            this.setState({
                carPriceMin: null,
                carPriceMax: null,
            })
        }
        if(item.key === 'title'){
            this.setState({
                title: null,
            })
        }
        if(item.key === 'carOutColor'){
            this.state.carOutColor.map((color, index)=>{
                if(item.value === color){
                    this.state.carOutColor.splice(index,1)
                }
            })
        }
        if(item.key === 'carInColor'){
            this.state.carInColor.map((color, index)=>{
                if(item.value === color){
                    this.state.carInColor.splice(index,1)
                }
            })
        }
        if(item.key === 'zyCity'){
            this.setState({
                zyCity: null
            })
        }
        if(item.key === 'zyType'){
            this.setState({
                zyType: null
            })
        }

        if(temp.length === 1){
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshData()
        })
    }

    // 买手列表
    buyerList() {
        return (
            <LinearGradient style={{marginTop: 10}} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#F8F7F5', '#FAF3EC', '#FAEEDE']}>
                <View>
                    <View style={{flexDirection: 'row', justifyContent: 'space-between', paddingTop: 10, paddingHorizontal: 15}}>
                        <Text style={{fontSize: 16, color: '#333333'}}>找买手</Text>
                        <Text style={{fontSize: 14, color: '#999999'}} onPress={() => {
                            navigation.navigate('BuyerListPage')
                        }}>查看全部 {'>'}</Text>
                    </View>
                    <View style={{borderBottomWidth: 1, borderBottomColor: '#e4e4e4', marginHorizontal: 10, marginVertical: 10}}></View>
                    {this.state.selectedTab === 1 ?
                        <View style={{borderBottomWidth: 1, borderBottomColor: '#e5e5e5', paddingBottom: 10}}>
                            <FlatList
                                data={this.state.buyerLists}
                                renderItem={this.buyerItemView.bind(this)}
                                keyExtractor={item => item[0]?.id || Math.random().toString()}
                                horizontal
                                showsHorizontalScrollIndicator={false}
                                ListEmptyComponent={this.renderBuyerEmpty.bind(this)}
                            />
                        </View>
                        :
                        <View style={{borderBottomWidth: 1, borderBottomColor: '#e5e5e5', paddingBottom: 10}}>
                            <FlatList
                                data={this.state.myFollowBuyerList}
                                renderItem={this.buyerFollowItemView.bind(this)}
                                keyExtractor={item => item.id}
                                horizontal
                                showsHorizontalScrollIndicator={false}
                                ListEmptyComponent={this.renderBuyerEmpty.bind(this)}
                            />
                        </View>
                    }
                </View>
            </LinearGradient>


        )
    }

    buyerFollowItemView({item, index}){
        return (
            <View key={item.id + 'b'}>
                <TouchableOpacity
                    key={index}
                    activeOpacity={0.7}
                    onPress={() => {
                        if(item.buyerId === Constant.userInfo.buyerId){
                            navigation.navigate('BuyerDetailPage', {
                                buyerId: item.buyerId
                            })
                        }else {
                            navigation.navigate('BuyerInfoPage', {
                                buyerId: item.buyerId
                            })
                        }
                    }}
                >
                    <View style={{flexDirection:'column', alignItems: 'center', marginLeft:15}}>
                        {item?.avatar  ? (
                            <Image
                                style={{width: 65, height: 65, borderRadius: 50}}
                                source={{
                                    uri: getImgUrl(item?.avatar),
                                }}
                            />
                        ) : (
                            <Image
                                source={require('source/image/seekCenter/default_avatar.png')}
                                style={{width: 65, height: 65, borderRadius: 50}}
                            />
                        )}

                        <Text numberOfLines={1} style={{fontSize: 14, color: '#333', marginTop: 11}}>{item?.fullname || '暂无'}</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    buyerItemView({item, index}) {
        // 确保 item 是数组
        if (!Array.isArray(item)) {
            console.error('Expected item to be an array but got:', item);
            return null;
        }
        return (
            <View style={styles.buyerItemContainer} key={item.id + ''}>
                {item.map((user, uIdx) => (
                    <TouchableOpacity
                        key={`${index}-${uIdx}`}
                        style={styles.buyerItemTouchableOpacity}
                        activeOpacity={0.7}
                        onPress={() => {
                            if(user.buyerId === Constant.userInfo.buyerId){
                                navigation.navigate('BuyerDetailPage', {
                                    buyerId: user.buyerId
                                })
                            }else {
                                navigation.navigate('BuyerInfoPage', {
                                    buyerId: user.buyerId
                                })
                            }
                        }}
                    >
                        <View style={styles.buyerItemAvatarContainer}>

                            {user?.avatar  ? (
                                <Image
                                    style={styles.buyerItemAvatar}
                                    source={{
                                        uri: getImgUrl(user?.avatar),
                                    }}
                                />
                            ) : (
                                <Image
                                    style={styles.buyerItemAvatar}
                                    source={require('source/image/seekCenter/default_avatar.png')}
                                />
                            )}

                        </View>

                        <View style={styles.buyerItemTextContainer}>
                            <View style={{flexDirection: 'row'}}>
                                <Text numberOfLines={1} style={styles.buyerItemNameText}>
                                    {user?.fullname || '暂无'}
                                </Text>
                                <View style={{width: 5}} />
                                <TouchableOpacity activeOpacity={0.7} onPress={() => {
                                    navigation.navigate('CompanyInfoPage', {
                                        merchantId: user?.merchantId,
                                    });
                                }}>
                                    <Text numberOfLines={1} style={styles.buyerItemStoreText}>
                                        @{user?.merchantAbbreviation || '暂无'}
                                    </Text>
                                </TouchableOpacity>

                            </View>
                            <Text numberOfLines={1} style={styles.buyerItemDescriptionText}>{user?.preferences || '暂无'}</Text>
                        </View>
                    </TouchableOpacity>
                ))}
            </View>
        )
    }

    renderList() {
        return (
            <View
                style={{
                    flex: 1,
                    // marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.seekingList}
                    renderItem={this.renderItemView.bind(this)}
                    keyExtractor={item => item?.id || Math.random().toString()} // 使用唯一键
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />
            </View>
        );
    }

    renderItemView({item, index}) {
        return (
            <View style={styles.itemContainer}>
                <SeekItemView
                    key={item.id}
                    item={item}
                    buyerId={Constant.userInfo.buyerId}
                    onPress={()=>{
                        if(item.buyerId === Constant.userInfo.buyerId){
                            navigation.navigate('SeekingDetailPage', {
                                id: item.id,
                                carMatchCount: item.carMatchCount,
                            });
                        }else {
                            navigation.navigate('SeekingInfoPage', {
                                id: item.id,
                                carMatchCount: item.carMatchCount,
                            });
                        }
                    }}
                    navigation={navigation}
                    onPressDel={() => {
                        this.setState({
                            deleteId: item.id,
                            showAlertData: {
                                title: '确定删除求购信息?',
                                cancelBtnText: '取消',
                                sureBtnText: '确定',
                                type: 'delete'
                            },
                            showAlertCommonView: true,
                        })
                    }}
                    onPressUpDown={() => {
                        if(item.status === 1){ // 进行下架操作
                            this.setState({
                                upCarPurchaseId: item.id,
                                showAlertData: {
                                    title: '确定下架求购信息?',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'down'
                                },
                                showAlertCommonView: true,
                            })
                        }else if (item.status === 2) { // 上架操作
                            this.setState({
                                upCarPurchaseId: item.id,
                                showAlertData: {
                                    title: '确定上架求购信息?',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'up'
                                },
                                showAlertCommonView: true,
                            })
                        }
                    }}
                    onPressEdit={() => {
                        navigation.navigate('ApplyCarFormPage', {
                            id: item.id,
                            fromPage: 'SeekingListPage',
                        });
                    }}
                ></SeekItemView>
            </View>
        );
    }

    renderListZY() {
        return (
            <View
                style={{
                    flex: 1,
                    // marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 50 : 50,
                }}>
                <FlatList
                    data={this.state.zhuanYinList}
                    renderItem={this.renderItemViewZY.bind(this)}
                    keyExtractor={item => item?.id || Math.random().toString()} // 使用唯一键
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />
            </View>
        );
    }

    renderItemViewZY({item, index}) {
        return (
            <View style={styles.itemContainerZy}>
                <ZhuanYinItemView
                    item={item}
                    title={item.merchantAbbreviation || ''}
                    image={item.merchantLogoPic || ''}
                    buyNum={item.buyerCount || 0}
                    authenCode={item.merchantAuthenCode || ''}
                    address={item.merchantAddress || ''}
                    city={item.merchantCityShortName || ''}
                    category={item.specializedTitle || ''}
                    onPress={()=>{
                        navigation.navigate('CompanyInfoPage', {
                            merchantId: item.merchantId,
                            category: item.specializedTitle || '',
                        });
                    }}></ZhuanYinItemView>
            </View>
        );
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(100)}} />;
    }

    renderBuyerEmpty() {
        return (
            <View style={{
                width: screenW,
                justifyContent: 'center',
                alignItems: 'center',
            }}>
                <Text style={{
                    fontSize: 16,
                }}>暂无数据</Text>
            </View>
        );
    }

    //刷新数据
    refreshData = () => {
        if(this.state.selectedTab === 3){
            this.setState(
                {
                    isRefresh: true,
                    pageNo: 1,
                    zhuanYinList: [],
                },
                function () {
                    this.getZhuanYinList();
                },
            );
        }else {
            this.setState(
                {
                    isRefresh: true,
                    pageNo: 1,
                    seekingList: [],
                },
                function () {
                    this.getSeekingList();
                },
            );
        }

    };

    // 底部加载更多
    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot !== 0) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1,
            },
            function () {
                if(this.state.selectedTab === 3){
                    if (this.state.zhuanYinList.length == 0) {
                        return null;
                    }
                    this.getZhuanYinList();
                }else {
                    if (this.state.seekingList.length == 0) {
                        return null;
                    }
                    this.getSeekingList();
                }
            },
        );
    }

    updateSeekingList(ids) {
        let param = {
            pageNo: 1,
            pageSize: 100,
            ids: ids,
        };

        let uri = HttpUrls.seekingQueryPage;
        if(this.state.selectedTab === 2){
            uri = HttpUrls.myFollowBuyerQueryPage;
        }
        HttpUtils.postRequest(uri, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        const list = [...this.state.seekingList]
                        list.map(item => {
                            resultList.map(item2 => {
                                if(item.id === item2.id){
                                    item.contactNum = item2.contactNum;
                                }
                            })
                        })
                        // console.log('update', list)
                        this.setState({
                            seekingList: list,
                        });
                    }
                }
            })
            .catch(error => {});
    }

    // 获取求购信息
    getSeekingList() {
        let param = {
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
        };
        if(this.state.areaId){
            param.areaId = this.state.areaId;
        }
        if(this.state.brandId){
            param.brandId = this.state.brandId;
        }
        if(this.state.mileageMin){
            param.carMileageMin = this.state.mileageMin;
        }
        if(this.state.mileageMax){
            param.carMileageMax = this.state.mileageMax;
        }
        if(this.state.registerDateBegin){
            param.carAgeMin = this.state.registerDateBegin;
        }
        if(this.state.registerDateEnd){
            param.carAgeMax = this.state.registerDateEnd;
        }
        if(this.state.carPriceMin){
            param.carPriceMin = this.state.carPriceMin;
        }
        if(this.state.carPriceMax){
            param.carPriceMax = this.state.carPriceMax;
        }
        if(this.state.carOutColor && this.state.carOutColor.length > 0){
            param.carOutColor = this.state.carOutColor;
        }
        if(this.state.carInColor && this.state.carInColor.length > 0){
            param.carInColor = this.state.carInColor;
        }
        if(this.state.title){
            param.title = this.state.title;
        }

        // 需要统计匹配的数量
        param.optionShowCarNum = 1;

        console.log('getSeekingListparam === ', param)

        let uri = HttpUrls.seekingQueryPage;
        if(this.state.selectedTab === 2){
            uri = HttpUrls.myFollowBuyerQueryPage;
        }

        // 排序
        // param.orderBy = 'upTime';
        // param.orderByAsc = 0;
        param.orderColumns = [{column:"up_time",orderAsc:false}]

        HttpUtils.postRequest(uri, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            seekingList: this.state.seekingList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            });
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch(error => {});
    }

    // 获取专营类型
    getZhuanYinType() {
        HttpUtils.getRequest(HttpUrls.zhanYinTypeList, {})
            .then(result => {
                let data = result.data;
                if (data) {
                    const dataList = data.map(item => {
                        return item.title
                    });
                    this.setState({
                        zhuanYinType: dataList,
                    });
                }
            })
            .catch(error => {}).finally(()=>{});
    }
    // 获取专营类型
    getZhuanYinCity() {
        HttpUtils.getRequest(HttpUrls.zhanYinCityList, {})
            .then(result => {
                let data = result.data;
                if (data) {
                    // console.log('getZhuanYinCity', data)
                    const dataList = data.map(item => {
                        return item.name
                    });
                    this.setState({
                        zhuanYinCity: dataList,
                    });
                }
            })
            .catch(error => {}).finally(()=>{});
    }

    // 获取专营数据
    getZhuanYinList() {
        let param = {
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
        };
        if(this.state.zyCity){
            param.cityName = this.state.zyCity;
        }
        if(this.state.zyType){
            param.title = this.state.zyType;
        }


        console.log('getZhuanYinList === ', param)

        let uri = HttpUrls.zhanYinMerchantList;

        HttpUtils.postRequest(uri, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            zhuanYinList: this.state.zhuanYinList.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            });
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch(error => {}).finally(() => {});
    }

    // 买手列表获取
    getBuyerList() {
        this.Loading.show()
        HttpUtils.getRequest(HttpUrls.getRecommendBuyerList)
            .then(result => {
                if(result.code === 0){
                    console.log('getBuyerList=====', result.data)
                    if(result.data && result.data.length > 0){
                        let data = result.data;
                        const pairedData = [];
                        for (let i = 0; i < data.length; i += 2) {
                            const pair = [];
                            if (data[i]) pair.push(data[i]);
                            if (data[i + 1]) pair.push(data[i + 1]);
                            if (pair.length > 0) pairedData.push(pair);
                        }
                        this.setState({
                            buyerLists: pairedData
                        })
                    }
                }
            })
            .catch(error => {}).finally(() => {
            this.Loading.hide()
        });
    }

    // 我关注的买手列表
    getMyFollowBuyerList() {
        this.Loading.show()
        HttpUtils.getRequest(HttpUrls.getMyFollowBuyerList)
            .then(result => {
                if(result.code === 0){
                    console.log('getMyFollowBuyerList=====', result.data)
                    if(result.data){
                        this.setState({
                            myFollowBuyerList: result.data,
                        });
                    }
                }
            })
            .catch(error => {}).finally(()=>{
            this.Loading.hide()
        });
    }

    // 检查买手是否已经完善标签
    checkUserIsBuyer = () => {
        // 页面数据
        this.refreshData();
        this.getBuyerList();
        this.getMyFollowBuyerList()
        if(Constant.userInfo.buyerId > 0){
            HttpUtils.getRequest(HttpUrls.checkHaveTage)
                .then(result => {
                    // console.log('checkUserIsBuyer', result);
                    if (result && result.code == 0) {
                        // 请求成功
                        const isBuyer = result.data; // 假设返回的数据结构中有 isBuyer 字段
                        // 可以根据 isBuyer 的值做进一步处理，比如跳转或提示
                        if (!isBuyer) {
                            console.log("用户未完善标签");
                            // 跳转到标签完善页面
                            navigation.navigate('BuyerSetLabelPage');
                        }
                    } else {
                        console.error("请求失败:", result.message);
                    }
                })
                .catch(error => {
                    console.error("请求错误:", error);
                });
        }
    };

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    // 顶部tab切换
    tabContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        // backgroundColor: 'red',
    },
    tabItem: {
        justifyContent: 'flex-start',
        alignItems: 'center',
        // paddingHorizontal: 10,
    },
    tabText: {
        fontSize: 16,
        color: '#333333',
    },
    tabTextActive: {
        color: '#ffcd00',
    },
    // 主要颜色
    tabActiveBackground: {
        backgroundColor: '#ffcd00',
    },
    underline: {
        height: 4,
        width: '100%',
        backgroundColor: '#ffffff',
        marginTop: 4,
    },

    // 右侧搜索样式
    topRightContain: {
        // paddingRight: 12,
        width: '100%',
        height: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    iconImg: {
        width: 24,
        height: 24
    },
    iconImgUser21: {
        width: 21,
        height: 21
    },
    iconImgUser: {
        width: 22,
        height: 22
    },
    iconImgUser23: {
        width: 23,
        height: 23
    },

    // 选项过滤
    filterContain: {
        width: '100%',
        height: 46,
        backgroundColor: '#fff',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 5,
    },
    filterItem: {
        flex: 1,
        marginHorizontal: 2,
        height: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    filterImg: {
        width: 20,
        height: 20,
    },
    filterText: {
        fontSize: 14,
        color: '#666666'
    },

    // 底部加载更多
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6',
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },


    // 求购列表
    itemContainer:{
        marginHorizontal: 8,
        borderRadius: 5,
        marginTop: 10,
    },

    // 买手列表
    buyerListContain: {
        // backgroundColor: 'red',
        marginTop: 10,
    },
    buyerItemContainer: {
        marginLeft: 15,
    },
    buyerItemTouchableOpacity: {
        flexDirection: 'row',
        alignItems: 'center',
        width: 150,
        marginBottom: 11,
    },
    buyerItemAvatarContainer: {
        width: 48,
    },
    buyerItemAvatar: {
        width: 42,
        height: 42,
        borderRadius: 50,
    },
    buyerItemTextContainer: {
        overflow: 'hidden',
        width: 100,
    },
    buyerItemNameText: {
        color: '#333',
        fontSize: 14,
    },
    buyerItemStoreText: {
        color: '#FFA500',
        fontSize: 12,
        // width: 60,
    },
    buyerItemDescriptionText: {
        fontSize: 13,
        color: '#666666',
        marginTop: 4,
    },

    // 筛选
    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 5,
        paddingVertical: 5,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 10,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 10,
        height: 10,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 12,
        height: 12,
        marginRight: 2,
        resizeMode: 'contain'
    },


    // 专营列表
    itemContainerZy:{
        marginHorizontal: 8,
        borderRadius: 5,
        marginTop: 10,
    },

});
